//
//  ARTWatchHistorySleepController.m
//  ChartsDemo
//
//  Created by 刘权 on 2021/10/13.
//

#import "ARTWatchHistorySleepController.h"
// views
#import "ARTWatchHistorySleepTopView.h"
#import "ARTWatchHistorySleepYangJianView.h"
#import "ARTWatchHistoryDailySpoView.h"
#import "ARTWatchHistoryCommonValueView.h"
#import "ARTWatchHistorySleepDisView.h"
#import "ARTWatchHistorySleepDis2View.h"
#import "ARTWatchHistorySleepStageView.h"
#import "ARTWatchSleepTextView.h"
#import "ARTWatchSleepResultView.h"
#import "ARTPDFHelper.h"

@interface ARTWatchHistorySleepController ()

// scrollView
@property (strong, nonatomic)  YDHBaseScrollView *scrollView;
// ARTWatchHistorySleepTopView
@property (strong, nonatomic)  ARTWatchHistorySleepTopView *topView;
// ARTWatchHistorySleepYangJianView
@property (strong, nonatomic)  ARTWatchHistorySleepYangJianView *yangJianView;
// ARTWatchHistoryDailySpoView
@property (strong, nonatomic)  ARTWatchHistoryDailySpoView *spoChartView;
// ARTWatchHistoryCommonValueView
@property (strong, nonatomic)  ARTWatchHistoryCommonValueView *spoView;
// ARTWatchHistorySleepDis2View
@property (strong, nonatomic)  ARTWatchHistorySleepDis2View *spoDisView;
// ARTWatchHistoryDailySpoView
@property (strong, nonatomic)  ARTWatchHistoryDailySpoView *hrChartView;
// ARTWatchHistoryCommonValueView
@property (strong, nonatomic)  ARTWatchHistoryCommonValueView *hrView;
// ARTWatchHistorySleepDisView
@property (strong, nonatomic)  ARTWatchHistorySleepDisView *hrDisView;
// ARTWatchHistoryDailySpoView
@property (strong, nonatomic)  ARTWatchHistorySleepStageView *sleepChartView;
// ARTWatchHistoryCommonChartTitleView
@property (strong, nonatomic)  ARTWatchHistoryCommonChartTitleView *sleepTitleView;
// ARTWatchHistoryCommonValueView
@property (strong, nonatomic)  ARTWatchHistoryCommonValueView *sleepView;
@property (strong, nonatomic)  ARTWatchSleepTextView *textView0;
@property (strong, nonatomic)  ARTWatchSleepTextView *textView1;
@property (strong, nonatomic)  ARTWatchSleepResultView *resultView;
@property (strong, nonatomic)  ARTWatchSleepTextView *textView2;
@property (strong, nonatomic)  ARTWatchSleepTextView *textView3;

@property (strong, nonatomic)  UIButton *rightButton;

@end

@implementation ARTWatchHistorySleepController

#pragma mark--THE LIFE CYCLE
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    J_Add_Notify(self, @selector(refreshLanguage), ART_Notify_LanguageChanged, nil);
    [self refreshLanguage];
    NSLog(@"睡眠报告模型数据receiveModel=%@",[_receiveModel modelToJSONString]);
}

- (void)initSubviews{
    [super initSubviews];
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.rightButton];
    
    [self.view addSubview:self.scrollView];
    
    [_scrollView appendOneItemView:self.topView];
    [_scrollView appendOneItemView:self.yangJianView];
    [_scrollView appendOneItemView:self.spoChartView];
    
    [_scrollView appendOneItemView:self.spoView];
    [_scrollView appendOneItemView:self.spoDisView];
    [_scrollView appendOneItemView:self.hrChartView];
    
    [_scrollView appendOneItemView:self.hrView];
    [_scrollView appendOneItemView:self.hrDisView];
    
    [_scrollView appendOneItemView:self.sleepChartView];
    [_scrollView appendOneItemView:self.sleepTitleView];
    [_scrollView appendOneItemView:self.sleepView];
    
    [_scrollView appendOneItemView:self.textView0];
    [_scrollView appendOneItemView:self.textView1];
    [_scrollView appendOneItemView:self.resultView];
    [_scrollView appendOneItemView:self.textView2];
    [_scrollView appendOneItemView:self.textView3];
    
    YDHBaseItemView *tempView = [[YDHBaseItemView alloc]initWithFrame:J_Frame(0, 0, J_SCREEN_WIDTH, J_TabBarHeight+10)];
    tempView.backgroundColor = _scrollView.backgroundColor;
    [_scrollView appendOneItemView:tempView];
    
    [self configureForView];
}

- (void)dealloc{
    J_Remove_Notify(self);
}

/// 返回按钮事件
- (void)hookBackBarButtonAction:(UIButton *)sender{
    if (_popClass) {
        [ARTNavigation popToControllerWithName:_popClass animated:YES];
    }else{
        [ARTNavigation closeViewControllerAnimated:YES];
    }
}

#pragma mark--PRIVATE METHOD
- (void)configureForView{
    if (!_receiveModel) {
        return;
    }
    // 诊断结果视图
    _topView.hisModel = _receiveModel;
    
    NSArray *datasList = @[];
    
    NSString *filePath = [J_Path_Document stringByAppendingPathComponent:@"watchHistory"];
    NSString *watchPath = [filePath stringByAppendingPathComponent:_receiveModel.dataFileName];
    NSString *jsonString = [NSString stringWithContentsOfFile:watchPath encoding:NSUTF8StringEncoding error:nil];
    if (jsonString) {
        jsonString = [RSAEncryptor decryptSubsectionString:jsonString privateKey:ART_Prikey];
        datasList = [NSArray modelArrayWithClass:[ARTWathDataModel class] json:jsonString];
    }
    NSLog(@"睡眠报告模型数据datasList=%@",datasList);
    
    // 血氧
    [self configureOximiter:datasList];
    
    // 心率
    [self configureHeartRate:datasList];
    
    // 睡眠分布
    [self configureSleepStages];
    
//    NSString *spoTitle = @"-正常";
//    UIColor *spoColor = [UIColor colorWithString:@"#0DA462"];
//    NSString *prTitle = @"-正常";
//    UIColor *prColor = [UIColor colorWithString:@"#0DA462"];
//    if ((_receiveModel.spo2_95+_receiveModel.spo2_90+_receiveModel.spo2_85+_receiveModel.spo2_80)*1.0/datasList.count > 0.05) {
//        spoTitle = @"-过低";
//        spoColor = [UIColor colorWithString:@"#E50C0C"];
//    }
//    if (_receiveModel.pr_100*1.0/datasList.count > 0.05) {
//        prTitle = @"-过高";
//        prColor = [UIColor colorWithString:@"#E50C0C"];
//    }
//    if (_receiveModel.pr_60*1.0/datasList.count > 0.05) {
//        prTitle = @"-过低";
//        prColor = [UIColor colorWithString:@"#E50C0C"];
//    }
//    _spoChartView.titleView.detailLabel.text = spoTitle;
//    _spoChartView.titleView.detailLabel.textColor = spoColor;
//    _hrChartView.titleView.detailLabel.text = prTitle;
//    _hrChartView.titleView.detailLabel.textColor = prColor;
}

- (void)configureOximiter:(NSArray *)datasList{
    _spoChartView.titleView.titleLabel.text = [NSString stringWithFormat:@"%@(%@)",FYLocalizedString(@"oxygen_warning_sp_n", @""),@"%"];
    _spoChartView.titleView.showType = 1;
    _spoChartView.titleView.helpBlock = ^{
        
    };
    // 绘制血氧饱和度图
    _spoChartView.chartView.lineColor = J_ColorFromHEX(0x0095B6);
    _spoChartView.chartView.yLabelArray = @[
        @"70",
        @"80",
        @"90",
        @"100"
    ];
    _spoChartView.chartView.xLabelArray = [self timeTitleArray];
    NSMutableArray *dataSets = [NSMutableArray array];
    NSInteger minSop2 = _receiveModel.spo2Min;//MAX(70, _receiveModel.spo2Min);
    NSInteger maxSpo2 = _receiveModel.spo2Max;//MIN(100, _receiveModel.spo2Max);
    for (ARTWathDataModel *temp in datasList) {
        if (temp.spo2 >= minSop2 && temp.spo2 <= maxSpo2) {
            [dataSets addObject:@(temp.spo2)];
        }
    }
    _spoChartView.chartView.valueArray = dataSets;
    _spoChartView.chartView.chartSnapshotLayerImage = [_receiveModel sleepSpo2ChartImage];
    J_WeakSelf(self)
    _spoChartView.chartView.chartSnapshotCallbeck = ^{
        J_StrongSelf(self)
                     [self.receiveModel storeSleepSpo2ChartImage:self.spoChartView.chartView.chartSnapshotLayerImage];
    };
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.spoChartView.chartView startDrawing3];
    });
//    _spoChartView.chartView.valueArray = dataSets;
//    _spoChartView.chartView.maxValue = 100;
//    _spoChartView.chartView.minValue = 70;
//    _spoChartView.chartView.canSkip = YES;
//    _spoChartView.chartView.skip_max = 100;
//    _spoChartView.chartView.skip_min = 70;
//    [_spoChartView.chartView startDrawing];
    
    NSMutableAttributedString *odi = [_spoView attributeTextWithValue:[NSString stringWithFormat:@"%.1f",_receiveModel.odi] unit:@"" message:FYLocalizedString(@"sleep_watch_text_odi", @"")];
    UIImage *image = J_ImageNamed(@"nav_ic_help2");
    NSMutableAttributedString *imageAtt = [NSMutableAttributedString attachmentStringWithContent:image contentMode:UIViewContentModeCenter attachmentSize:CGSizeMake(image.size.width, image.size.height) alignToFont:J_MediumFont(10) alignment:YYTextVerticalAlignmentCenter];
    [imageAtt setTextHighlightRange:imageAtt.rangeOfAll color:nil backgroundColor:[UIColor whiteColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        NSString *title = FYLocalizedString(@"sleep_watch_text_odi", @"");
        NSMutableAttributedString *contentAttribute = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@\n\n",FYLocalizedString(@"sleep_watch_knowledge1", @"")] attributes:@{NSForegroundColorAttributeName:J_ColorFromHEX(0x222222),NSFontAttributeName:J_Font(16)}];
        [contentAttribute appendAttributedString:[[NSAttributedString alloc] initWithString:FYLocalizedString(@"sleep_watch_knowledge_ox4", @"") attributes:@{NSForegroundColorAttributeName:J_ColorFromHEX(0x222222),NSFontAttributeName:J_Font(16)}]];
        [contentAttribute appendAttributedString:[[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"<=5%@/h\n",FYLocalizedString(@"sleep_watch_odi2", @"")] attributes:@{NSForegroundColorAttributeName:J_ColorFromHEX(0x0DA462),NSFontAttributeName:J_Font(16)}]];
        [contentAttribute appendAttributedString:[[NSAttributedString alloc] initWithString:FYLocalizedString(@"sleep_watch_knowledge_ox5", @"") attributes:@{NSForegroundColorAttributeName:J_ColorFromHEX(0x222222),NSFontAttributeName:J_Font(16)}]];
        [contentAttribute appendAttributedString:[[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"5-15%@/h\n",FYLocalizedString(@"sleep_watch_odi2", @"")] attributes:@{NSForegroundColorAttributeName:J_ColorFromHEX(0xFFE84A),NSFontAttributeName:J_Font(16)}]];
        [contentAttribute appendAttributedString:[[NSAttributedString alloc] initWithString:FYLocalizedString(@"sleep_watch_knowledge_ox6", @"") attributes:@{NSForegroundColorAttributeName:J_ColorFromHEX(0x222222),NSFontAttributeName:J_Font(16)}]];
        [contentAttribute appendAttributedString:[[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"15-30%@/h\n",FYLocalizedString(@"sleep_watch_odi2", @"")] attributes:@{NSForegroundColorAttributeName:J_ColorFromHEX(0xFF9627),NSFontAttributeName:J_Font(16)}]];
        [contentAttribute appendAttributedString:[[NSAttributedString alloc] initWithString:FYLocalizedString(@"sleep_watch_knowledge_ox7", @"") attributes:@{NSForegroundColorAttributeName:J_ColorFromHEX(0x222222),NSFontAttributeName:J_Font(16)}]];
        [contentAttribute appendAttributedString:[[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@">30%@/h\n",FYLocalizedString(@"sleep_watch_odi2", @"")] attributes:@{NSForegroundColorAttributeName:J_ColorFromHEX(0xE50C0C),NSFontAttributeName:J_Font(16)}]];
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
        paragraphStyle.lineSpacing = 6;
        [contentAttribute addAttributes:@{NSParagraphStyleAttributeName:paragraphStyle} range:contentAttribute.rangeOfAll];
        ARTWatchHistoryAlertView *view = [[ARTWatchHistoryAlertView alloc]initWithTitle:title messageAttribute:contentAttribute];
        [view show];
    }];
    [odi appendAttributedString:imageAtt];
    _spoView.value1Label.attributedText = odi;
    
    _spoView.value2Label.attributedText = [_spoView attributeTextWithValue:@(_receiveModel.spo2Avg).stringValue unit:@"%" message:[self filterTitle:FYLocalizedString(@"oxygen_average_value", @"")]];
    _spoView.value3Label.attributedText = [_spoView attributeTextWithValue:@(_receiveModel.spo2Min).stringValue unit:@"%" message:[self filterTitle:FYLocalizedString(@"oxygen_mini_value", @"")]];
    
    // 血氧分布
    _spoDisView.titleLabel.text = FYLocalizedString(@"sleep_watch_knowledge_title3", @"");
    
    _spoDisView.oneLabel1.text = FYLocalizedString(@"sleep_watch_range", @"");
    _spoDisView.oneLabel2.text = [NSString stringWithFormat:@"%@(%@)",FYLocalizedString(@"oxygen_time", @""),FYLocalizedString(@"sleep_watch_longtime", @"")];//@"时长(分钟)";
    _spoDisView.oneLabel3.text = FYLocalizedString(@"sleep_watch_percentage", @"");
    _spoDisView.oneLabel3.numberOfLines = 2;
    
    NSInteger spo2_max95 = _receiveModel.spo2_max95;
    if (maxSpo2 < 95) {
        spo2_max95 = 0;
    }
    _spoDisView.twoLabel1.text = @"≥95";
    _spoDisView.twoLabel2.text = [Tool get_MMSS_FromSS:spo2_max95];
    _spoDisView.twoLabel3.text = [NSString stringWithFormat:@"%.2f",spo2_max95*100.0/datasList.count];
    
    NSInteger spo2_95 = _receiveModel.spo2_95;
    if (minSop2 >= 95) {
        spo2_95 = 0;
    }
    _spoDisView.threeLabel1.text = @"<95";
    _spoDisView.threeLabel2.text = [Tool get_MMSS_FromSS:spo2_95];
    _spoDisView.threeLabel3.text = [NSString stringWithFormat:@"%.2f",spo2_95*100.0/datasList.count];
    
    NSInteger spo2_90 = _receiveModel.spo2_90;
    if (minSop2 >= 90) {
        spo2_90 = 0;
    }
    _spoDisView.fourLabel1.text = @"<90";
    _spoDisView.fourLabel2.text = [Tool get_MMSS_FromSS:spo2_90];
    _spoDisView.fourLabel3.text = [NSString stringWithFormat:@"%.2f",spo2_90*100.0/datasList.count];
    
    NSInteger spo2_85 = _receiveModel.spo2_85;
    if (minSop2 >= 85) {
        spo2_85 = 0;
    }
    _spoDisView.fiveLabel1.text = @"<85";
    _spoDisView.fiveLabel2.text = [Tool get_MMSS_FromSS:spo2_85];
    _spoDisView.fiveLabel3.text = [NSString stringWithFormat:@"%.2f",spo2_85*100.0/datasList.count];
}

- (void)configureHeartRate:(NSArray *)datasList{
    _hrChartView.titleView.titleLabel.text = FYLocalizedString(@"sleep_watch_pr", @"");
    _hrChartView.titleView.showType = 2;
    // 绘制心率图
    _hrChartView.chartView.lineColor = J_ColorFromHEX(0x0095B6);
    _hrChartView.chartView.yLabelArray = @[
        @"0",
        @"50",
        @"100",
        @"150",
        @"200",
        @"250"
    ];
    _hrChartView.chartView.xLabelArray = [self timeTitleArray];
    NSMutableArray *dataSets = [NSMutableArray array];
    NSInteger minPr = MAX(0, _receiveModel.prMin);
    NSInteger maxPr = MIN(250, _receiveModel.prMax);
    for (ARTWathDataModel *temp in datasList) {
        if (temp.pr >= minPr && temp.pr <= maxPr) {
            [dataSets addObject:@(temp.pr)];
        }
    }
    _hrChartView.chartView.valueArray = dataSets;
    _hrChartView.chartView.chartSnapshotLayerImage = [_receiveModel sleepPrChartImage];
    J_WeakSelf(self)
    _hrChartView.chartView.chartSnapshotCallbeck = ^{
        J_StrongSelf(self)
                     [self.receiveModel storeSleepPrChartImage:self.hrChartView.chartView.chartSnapshotLayerImage];
    };
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.hrChartView.chartView startDrawing4];
    });
//    _hrChartView.chartView.valueArray = dataSets;
//    _hrChartView.chartView.maxValue = 250;
//    _hrChartView.chartView.minValue = 0;
//    _hrChartView.chartView.canSkip = YES;
//    _hrChartView.chartView.skip_max = 250;
//    _hrChartView.chartView.skip_min = 15;
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [self.hrChartView.chartView startDrawing];
//    });
    
    _hrView.value1Label.attributedText = [_hrView attributeTextWithValue:@(_receiveModel.prMax).stringValue unit:@"" message:[self filterTitle:FYLocalizedString(@"oxygen_heart_max_value", @"")]];
    _hrView.value2Label.attributedText = [_hrView attributeTextWithValue:@(_receiveModel.prAvg).stringValue unit:@"" message:[self filterTitle:FYLocalizedString(@"oxygen_heart_average_value", @"")]];
    _hrView.value3Label.attributedText = [_hrView attributeTextWithValue:@(_receiveModel.prMin).stringValue unit:@"" message:[self filterTitle:FYLocalizedString(@"oxygen_heart_mini_value", @"")]];
    
    // 心率分布
    _hrDisView.titleLabel.text = FYLocalizedString(@"sleep_watch_knowledge_title7", @"");
    
    _hrDisView.oneLabel1.text = FYLocalizedString(@"sleep_watch_pr_range", @"");
    _hrDisView.oneLabel2.text = [NSString stringWithFormat:@"%@(%@)",FYLocalizedString(@"oxygen_time", @""),FYLocalizedString(@"sleep_watch_longtime", @"")];
    _hrDisView.oneLabel3.text = FYLocalizedString(@"sleep_watch_percentage", @"");
    _hrDisView.oneLabel3.numberOfLines = 2;
    
    NSInteger pr_100 = _receiveModel.pr_100;
    if (maxPr <= 100) {
        pr_100 = 0;
    }
    NSInteger pr_60 = _receiveModel.pr_60;
    if (minPr >= 60) {
        pr_60 = 0;
    }
    _hrDisView.twoLabel1.text = @">100";
    _hrDisView.twoLabel2.text = [Tool get_MMSS_FromSS:pr_100];
    _hrDisView.twoLabel3.text = [NSString stringWithFormat:@"%.2f",pr_100*100.0/datasList.count];
    
    _hrDisView.threeLabel1.text = @"60-100";
    _hrDisView.threeLabel2.text = [Tool get_MMSS_FromSS:(datasList.count-pr_100-pr_60)];
    _hrDisView.threeLabel3.text = [NSString stringWithFormat:@"%.2f",(datasList.count-pr_100-pr_60)*100.0/datasList.count];
    
    _hrDisView.fourLabel1.text = @"<60";
    _hrDisView.fourLabel2.text = [Tool get_MMSS_FromSS:pr_60];
    _hrDisView.fourLabel3.text = [NSString stringWithFormat:@"%.2f",pr_60*100.0/datasList.count];
}

- (void)configureSleepStages{
    _sleepChartView.titleView.titleLabel.text = FYLocalizedString(@"sleep_watch_knowledge_title5", @"");
    _sleepChartView.titleView.detailLabel.hidden = YES;
    _sleepChartView.titleView.showType = 3;
    _sleepChartView.timeArray = [self timeTitleArray];
    NSMutableArray *dataSets = [NSMutableArray array];
    for (NSNumber *temp in _receiveModel.sleepStages) {
        [dataSets addObject:temp];
    }
    _sleepChartView.valueArray = dataSets;
    _sleepChartView.longTime = _receiveModel.longTime;
    [_sleepChartView startDrawing];
//    // 绘制睡眠图
//    _sleepChartView.chartView.lineColor = J_ColorFromHEX(0x0095B6);
//    _sleepChartView.chartView.yLabelArray = @[
//        @"清醒",
//        @"浅睡",
//        @"深睡"
//    ];
//    _sleepChartView.chartView.xLabelArray = [self timeTitleArray];
//    NSMutableArray *dataSets = [NSMutableArray array];
//    for (NSNumber *temp in _receiveModel.sleepStages) {
//        [dataSets addObject:temp];
//    }
//    _sleepChartView.chartView.valueArray = dataSets;
//    _sleepChartView.chartView.maxValue = 2;
//    _sleepChartView.chartView.minValue = 0;
//    _sleepChartView.chartView.isZhi = YES;
//    [_sleepChartView.chartView startDrawing];
    
    NSArray *time1 = [[Tool getMMSSFromSS:_receiveModel.time_deep_sleep] componentsSeparatedByString:@":"];
    _sleepView.value1Label.attributedText = [_sleepView attributeTextWithHour:time1[0] minute:time1[1] message:FYLocalizedString(@"sleep_watch_deep", @"")];
    
    NSArray *time2 = [[Tool getMMSSFromSS:_receiveModel.time_light_sleep] componentsSeparatedByString:@":"];
    _sleepView.value2Label.attributedText = [_sleepView attributeTextWithHour:time2[0] minute:time2[1] message:FYLocalizedString(@"sleep_watch_shallow", @"")];
    
    NSArray *time3 = [[Tool getMMSSFromSS:_receiveModel.time_awake] componentsSeparatedByString:@":"];
    _sleepView.value3Label.attributedText = [_sleepView attributeTextWithHour:time3[0] minute:time3[1] message:FYLocalizedString(@"sleep_watch_sober", @"")];
}

- (NSArray *)timeTitleArray{
    long duration = _receiveModel.longTime/3;
    NSDate *startData = [NSDate j_dateWithString:_receiveModel.date format:@"yyyy/MM/dd HH:mm:ss"];
    NSDate *date2 = [startData j_dateByAddingSeconds:duration];
    NSDate *date3 = [startData j_dateByAddingSeconds:duration*2];
    NSDate *endDate = [startData j_dateByAddingSeconds:_receiveModel.longTime];
    NSString *string1 = [startData j_stringWithFormat:@"HH:mm:ss"];
    NSString *string2 = [date2 j_stringWithFormat:@"HH:mm:ss"];
    NSString *string3 = [date3 j_stringWithFormat:@"HH:mm:ss"];
    NSString *string4 = [endDate j_stringWithFormat:@"HH:mm:ss"];
    return @[SAFE_STRING(string4),SAFE_STRING(string3),SAFE_STRING(string2),SAFE_STRING(string1)];
}

- (NSString *)filterTitle:(NSString *)title{
    if ([title containsString:@"："]) {
        title = [title stringByReplacingOccurrencesOfString:@"：" withString:@""];
    }
    if ([title containsString:@":"]) {
        title = [title stringByReplacingOccurrencesOfString:@":" withString:@""];
    }
    return title;
}

#pragma mark--TARGET ACTION
- (void)refreshLanguage{
    self.title = FYLocalizedString(@"sleep_watch_sleep_test_report", @"");
}

- (void)rightAction{
    _scrollView.contentOffset = CGPointZero;
//    [_scrollView scrollsToTop];
    UIImage *image = [_scrollView snapshot];//[_scrollView qmui_snapshotLayerImage];
    if (!image) {
        [QMUITips showWithText:FYLocalizedString(@"share_fail", @"")];
        return;
    }
    // 分享的图片
//    UIImage *imageToShare = [image qmui_imageResizedInLimitedSize:image.size resizingMode:QMUIImageResizingModeScaleAspectFit scale:2.0];
    
//    UIImage *image1 = [image imageByCropToRect:CGRectMake(0, 0, image.size.width, image.size.height/3)];
//    UIImage *image2 = [image imageByCropToRect:CGRectMake(0, image.size.height/3, image.size.width, image.size.height/3)];
//    UIImage *image3 = [image imageByCropToRect:CGRectMake(0, image.size.height/3*2, image.size.width, image.size.height/3)];
    
//    UIImage *image1 = [image imageByCropToRect:CGRectMake(0, 0, image.size.width, self.spoView.bottom)];
//    UIImage *image2 = [image imageByCropToRect:CGRectMake(0, self.spoView.bottom, image.size.width, self.hrDisView.bottom-self.spoView.bottom)];
//    UIImage *image3 = [image imageByCropToRect:CGRectMake(0, self.hrDisView.bottom, image.size.width, self.textView1.bottom-self.hrDisView.bottom)];
//    UIImage *image4 = [image imageByCropToRect:CGRectMake(0, self.textView1.bottom, image.size.width, image.size.height-self.textView1.bottom)];
    
//    UIImage *image1 = [image imageByCropToRect:CGRectMake(0, 0, image.size.width, self.spoDisView.top)];
//    UIImage *image2 = [image imageByCropToRect:CGRectMake(0, self.spoDisView.top, image.size.width, self.sleepChartView.top-self.spoDisView.top)];
//    UIImage *image3 = [image imageByCropToRect:CGRectMake(0, self.sleepChartView.top, image.size.width, self.resultView.top-self.sleepChartView.top)];
//    UIImage *image4 = [image imageByCropToRect:CGRectMake(0, self.resultView.top, image.size.width, image.size.height-self.resultView.top)];
    
//    NSString * path =
//        [ARTPDFHelper createPDF:@[
//            [ARTPDFHelper imageWithTitle:@"<1>" fontSize:10 image:image1],
//            [ARTPDFHelper imageWithTitle:@"<2>" fontSize:10 image:image2],
//            [ARTPDFHelper imageWithTitle:@"<3>" fontSize:10 image:image3],
//            [ARTPDFHelper imageWithTitle:@"<4>" fontSize:10 image:image4],
//            ]];//[ARTPDFHelper createPDF:@[image1,image2,image3,image4]];
//    NSURL *file = [NSURL fileURLWithPath:path];
//    NSData *data = [NSData dataWithContentsOfFile:path];
    if (!image){
        [QMUITips showWithText:FYLocalizedString(@"share_fail", @"")];
        return;
    }
    
    NSArray *activityItems = @[image];
    UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];
    // 不出现在活动项目
    [self presentViewController:activityVC animated:YES completion:nil];
    // 分享之后的回调
    J_WeakSelf(activityVC)
    activityVC.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
        J_StrongSelf(activityVC)
        if (completed) {
            // 分享成功
            [activityVC dismissViewControllerAnimated:YES completion:nil];
//            [self.navigationController popViewControllerAnimated:NO];
//                [ARTNavigation closeViewControllerAnimated:NO];
            if (activityError) {
                [QMUITips showWithText:FYLocalizedString(@"share_fail", @"")];
            }else{
                [QMUITips showWithText:FYLocalizedString(@"share_success", @"")];
            }
        } else  {
            NSLog(@"cancled");
            //分享 取消
            [activityVC dismissViewControllerAnimated:YES completion:nil];
//            [self.navigationController popViewControllerAnimated:NO];
//                [ARTNavigation closeViewControllerAnimated:NO];
            [QMUITips showWithText:FYLocalizedString(@"share_cancel", @"")];
        }
    };
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark--Getter
- (YDHBaseScrollView *)scrollView{
    if (!_scrollView) {
        _scrollView = [[YDHBaseScrollView alloc]init];
        _scrollView.frame = CGRectMake(0, J_NavBarHeight, J_SCREEN_WIDTH, J_SCREEN_HEIGHT-J_NavBarHeight);
        _scrollView.backgroundColor = J_ColorFromHEX(0xF5F5F5);
        _scrollView.bounces = YES;
//        _scrollView.margin_bottom = 80;
    }
    return _scrollView;
}

- (ARTWatchHistorySleepTopView *)topView{
    if (!_topView) {
        _topView = [[ARTWatchHistorySleepTopView alloc]init];
        _topView.margin_top = 10;
        J_WeakSelf(self)
        _topView.heightChangedBlock = ^{
            J_StrongSelf(self)
            [self.scrollView updateAllItemViews];
        };
    }
    return _topView;
}

- (ARTWatchHistorySleepYangJianView *)yangJianView{
    if (!_yangJianView) {
        _yangJianView = [[ARTWatchHistorySleepYangJianView alloc]init];
        _yangJianView.margin_top = 10;
    }
    return _yangJianView;
}

- (ARTWatchHistoryDailySpoView *)spoChartView{
    if (!_spoChartView) {
        _spoChartView = [[ARTWatchHistoryDailySpoView alloc]init];
        _spoChartView.titleView.detailLabel.hidden = YES;
        _spoChartView.margin_top = 10;
    }
    return _spoChartView;
}

- (ARTWatchHistoryCommonValueView *)spoView{
    if (!_spoView) {
        _spoView = [[ARTWatchHistoryCommonValueView alloc]initWithFrame:J_Frame(15, 0, J_SCREEN_WIDTH-15*2, 88)];
        _spoView.margin_top = 10;
    }
    return _spoView;
}

- (ARTWatchHistorySleepDis2View *)spoDisView{
    if (!_spoDisView) {
        _spoDisView = [[ARTWatchHistorySleepDis2View alloc]init];
        _spoDisView.margin_top = 10;
    }
    return _spoDisView;
}

- (ARTWatchHistoryDailySpoView *)hrChartView{
    if (!_hrChartView) {
        _hrChartView = [[ARTWatchHistoryDailySpoView alloc]init];
        _hrChartView.titleView.detailLabel.hidden = YES;
        _hrChartView.margin_top = 10;
    }
    return _hrChartView;
}

- (ARTWatchHistoryCommonValueView *)hrView{
    if (!_hrView) {
        _hrView = [[ARTWatchHistoryCommonValueView alloc]initWithFrame:J_Frame(15, 0, J_SCREEN_WIDTH-15*2, 88)];
        _hrView.margin_top = 10;
    }
    return _hrView;
}

- (ARTWatchHistorySleepDisView *)hrDisView{
    if (!_hrDisView) {
        _hrDisView = [[ARTWatchHistorySleepDisView alloc]init];
        _hrDisView.margin_top = 10;
    }
    return _hrDisView;
}

- (ARTWatchHistorySleepStageView *)sleepChartView{
    if (!_sleepChartView) {
        _sleepChartView = [[ARTWatchHistorySleepStageView alloc]init];
        _sleepChartView.margin_top = 10;
    }
    return _sleepChartView;
}

- (ARTWatchHistoryCommonChartTitleView *)sleepTitleView{
    if (!_sleepTitleView) {
        _sleepTitleView = [[ARTWatchHistoryCommonChartTitleView alloc]initWithFrame:J_Frame(15, 0, J_SCREEN_WIDTH-15*2, 20)];
        _sleepTitleView.titleLabel.text = FYLocalizedString(@"sleep_watch_knowledge_title6", @"");
        _sleepTitleView.detailLabel.hidden = YES;
        _sleepTitleView.showType = 4;
        J_ViewRadius(_sleepTitleView, 10);
        _sleepTitleView.margin_top = 10;
    }
    return _sleepTitleView;
}

- (ARTWatchHistoryCommonValueView *)sleepView{
    if (!_sleepView) {
        _sleepView = [[ARTWatchHistoryCommonValueView alloc]initWithFrame:J_Frame(15, 0, J_SCREEN_WIDTH-15*2, 88)];
        _sleepView.margin_top = -12;
    }
    return _sleepView;
}

- (ARTWatchSleepTextView *)textView0{
    if (!_textView0) {
        _textView0 = [[ARTWatchSleepTextView alloc]initWithFrame:J_Frame(15, 0, J_SCREEN_WIDTH-15*2, 20)];
        _textView0.title = FYLocalizedString(@"sleep_watch_initial_impressions", @"");
        NSString *content = [self contentOfSleep];
        _textView0.content = content;
        _textView0.margin_top = 10;
        [_textView0 configureUI];
    }
    return _textView0;
}

- (ARTWatchSleepTextView *)textView1{
    if (!_textView1) {
        _textView1 = [[ARTWatchSleepTextView alloc]initWithFrame:J_Frame(15, 0, J_SCREEN_WIDTH-15*2, 20)];
        _textView1.title = FYLocalizedString(@"sleep_watch_syndrome", @"");
        _textView1.content = FYLocalizedString(@"Under normal circumstances, a clear airway allows air to enter and exit the lungs freely. In apnea patients, the upper airway is blocked during sleep and breathing is suspended for a few seconds to several minutes, up to hundreds of times per night, causing the patient ’s body to be deprived of oxygen and often wake up suddenly and making it difficult to fall asleep and get enough sleep.", @"");
        _textView1.margin_top = 10;
        [_textView1 configureUI];
    }
    return _textView1;
}

- (ARTWatchSleepResultView *)resultView{
    if (!_resultView) {
        _resultView = [[ARTWatchSleepResultView alloc]init];
        _resultView.margin_top = 10;
    }
    return _resultView;
}

- (ARTWatchSleepTextView *)textView2{
    if (!_textView2) {
        _textView2 = [[ARTWatchSleepTextView alloc]initWithFrame:J_Frame(15, 0, J_SCREEN_WIDTH-15*2, 20)];
        _textView2.title = FYLocalizedString(@"Common symptoms of sleep apnea hypopnea syndrome:", @"");
        _textView2.content = FYLocalizedString(@"Snoring and stopping breathing while sleeping will cause these symptoms,  such as repeatedly waking up with suffocation, sweating when sleeping, numbness in hands and feet, daytime drowsiness, dry mouth in the morning, headache, dizziness, arrhythmia, decreased work efficiency, palpitations and chest tightness at night, lack of concentration, increased nocturnal urination, unresponsiveness, memory loss, unexplained hypertension, decreased sexual function in men, change in temperament, anxiety, daytime fatigue, high blood lipids and blood sugar.", @"");
        _textView2.margin_top = 10;
        [_textView2 configureUI];
    }
    return _textView2;
}

- (ARTWatchSleepTextView *)textView3{
    if (!_textView3) {
        _textView3 = [[ARTWatchSleepTextView alloc]initWithFrame:J_Frame(15, 0, J_SCREEN_WIDTH-15*2, 20)];
        _textView3.title = FYLocalizedString(@"To clarify the occurrence of comorbidities and complications at the time of clinical diagnosis, OSAHS may cause the following diseases or problems:", @"");
        _textView3.content = FYLocalizedString(@"Causes or aggravates hypertension, respiratory failure, chronic obstructive pulmonary disease,Coronary heart disease, nocturnal angina and myocardial infarction, nocturnal attacks of bronchial asthma, nocturnal onset of severe arrhythmias, premature ventricular contractions, secondary erythrocytosis, tachycardia, sinus arrest, sinus block, increased blood viscosity, and atrioventricular block, enuresis, type II diabetes mellitus and insulin resistance, sexual dysfunction, impotence and decreased libido, cerebral thrombosis, cerebral hemorrhage, gastroesophageal reflux, seizures neurasthenia, dementia, hypertensive disorders of pregnancy or pre-eclampsia, psychiatric abnormalities, anxiety, depression, speech confusion, renal impairment, behavioral abnormalities, personality changes, hallucinations and hallucinations, hepatic impairment, overlap syndrome (COPD/bronchial asthma), obesity exacerbation, pulmonary hypertension and pulmonary heart disease, major traffic accidents, restless legs syndrome and periodic leg movements during sleep, Parkinson’s.", @"");
        _textView3.subContent = FYLocalizedString(@"This report is for reference only and is not intended as a basis for clinical diagnosis", @"");
        _textView3.margin_top = 10;
        [_textView3 configureUI];
    }
    return _textView3;
}

- (UIButton *)rightButton{
    if (!_rightButton) {
        _rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _rightButton.frame = J_FrameWithSize(40, 40);
        [_rightButton setImage:J_ImageNamed(@"nav_ic_share1") forState:UIControlStateNormal];
        [_rightButton addTarget:self action:@selector(rightAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _rightButton;
}

- (NSString *)contentOfSleep{
    NSInteger oxygenMini = self.receiveModel.spo2Min;
    CGFloat odi = self.receiveModel.odi;
    if(odi<5&&oxygenMini>=90){
        return FYLocalizedString(@"oxygen_healthy", @"");
    }

    if(odi<=15&&oxygenMini>=90){
//        return @"疑似呼吸暂停综合征 轻度";
        return [NSString stringWithFormat:@"%@%@",FYLocalizedString(@"sleep_watch_impressions1", @""),FYLocalizedString(@"oxygen_light", @"")];
    }

    if(odi<=30&&oxygenMini>=90){
//        return @"疑似呼吸暂停综合征 中度";
        return [NSString stringWithFormat:@"%@%@",FYLocalizedString(@"sleep_watch_impressions1", @""),FYLocalizedString(@"oxygen_moderate", @"")];
    }

    if(odi>30&&oxygenMini>=90){
//        return @"疑似呼吸暂停综合征 重度";
        return [NSString stringWithFormat:@"%@%@",FYLocalizedString(@"sleep_watch_impressions1", @""),FYLocalizedString(@"oxygen_severe", @"")];
    }

    if(odi<5&&oxygenMini<80){
//        return @"疑似低血氧症 重度";
        return [NSString stringWithFormat:@"%@%@",FYLocalizedString(@"sleep_watch_impressions2", @""),FYLocalizedString(@"oxygen_severe", @"")];
    }

    if(odi<5&&oxygenMini<85){
//        return @"疑似低血氧症 中度";
        return [NSString stringWithFormat:@"%@%@",FYLocalizedString(@"sleep_watch_impressions2", @""),FYLocalizedString(@"oxygen_moderate", @"")];
    }

    if(odi<5&&oxygenMini<90){
//        return @"疑似低血氧症 轻度";
        return [NSString stringWithFormat:@"%@%@",FYLocalizedString(@"sleep_watch_impressions2", @""),FYLocalizedString(@"oxygen_light", @"")];
    }


    if(odi<=15&&oxygenMini<80){
//        return @"疑似呼吸暂停综合征： 轻度  \n疑似低血氧症：重度";
        return [NSString stringWithFormat:@"%@%@\n%@%@",FYLocalizedString(@"sleep_watch_impressions1", @""),FYLocalizedString(@"oxygen_light", @""),FYLocalizedString(@"sleep_watch_impressions2", @""),FYLocalizedString(@"oxygen_severe", @"")];
    }

    if(odi<=15&&oxygenMini<85){
//        return @"疑似呼吸暂停综合征： 轻度  \n疑似低血氧症：中度";
        return [NSString stringWithFormat:@"%@%@\n%@%@",FYLocalizedString(@"sleep_watch_impressions1", @""),FYLocalizedString(@"oxygen_light", @""),FYLocalizedString(@"sleep_watch_impressions2", @""),FYLocalizedString(@"oxygen_moderate", @"")];
    }

    if(odi<=15&&oxygenMini<90){
//        return @"疑似呼吸暂停综合征： 轻度  \n疑似低血氧症：轻度";
        return [NSString stringWithFormat:@"%@%@\n%@%@",FYLocalizedString(@"sleep_watch_impressions1", @""),FYLocalizedString(@"oxygen_light", @""),FYLocalizedString(@"sleep_watch_impressions2", @""),FYLocalizedString(@"oxygen_light", @"")];
    }

    if(odi<=30&&oxygenMini<80){
//        return @"疑似呼吸暂停综合征： 中度  \n疑似低血氧症：重度";
        return [NSString stringWithFormat:@"%@%@\n%@%@",FYLocalizedString(@"sleep_watch_impressions1", @""),FYLocalizedString(@"oxygen_moderate", @""),FYLocalizedString(@"sleep_watch_impressions2", @""),FYLocalizedString(@"oxygen_severe", @"")];
    }

    if(odi<=30&&oxygenMini<85){
//        return @"疑似呼吸暂停综合征： 中度  \n疑似低血氧症：中度";
        return [NSString stringWithFormat:@"%@%@\n%@%@",FYLocalizedString(@"sleep_watch_impressions1", @""),FYLocalizedString(@"oxygen_moderate", @""),FYLocalizedString(@"sleep_watch_impressions2", @""),FYLocalizedString(@"oxygen_moderate", @"")];
    }

    if(odi<=30&&oxygenMini<90){
//        return @"疑似呼吸暂停综合征： 中度  \n疑似低血氧症：轻度";
        return [NSString stringWithFormat:@"%@%@\n%@%@",FYLocalizedString(@"sleep_watch_impressions1", @""),FYLocalizedString(@"oxygen_moderate", @""),FYLocalizedString(@"sleep_watch_impressions2", @""),FYLocalizedString(@"oxygen_light", @"")];
    }

    if(odi>30&&oxygenMini<80){
//        return @"疑似呼吸暂停综合征： 重度  \n疑似低血氧症：重度";
        return [NSString stringWithFormat:@"%@%@\n%@%@",FYLocalizedString(@"sleep_watch_impressions1", @""),FYLocalizedString(@"oxygen_severe", @""),FYLocalizedString(@"sleep_watch_impressions2", @""),FYLocalizedString(@"oxygen_severe", @"")];
    }

    if(odi>30&&oxygenMini<85){
//        return @"疑似呼吸暂停综合征： 重度  \n疑似低血氧症：中度";
        return [NSString stringWithFormat:@"%@%@\n%@%@",FYLocalizedString(@"sleep_watch_impressions1", @""),FYLocalizedString(@"oxygen_severe", @""),FYLocalizedString(@"sleep_watch_impressions2", @""),FYLocalizedString(@"oxygen_moderate", @"")];
    }

    if(odi>30&&oxygenMini<90){
//        return @"疑似呼吸暂停综合征： 重度  \n疑似低血氧症：轻度";
        return [NSString stringWithFormat:@"%@%@\n%@%@",FYLocalizedString(@"sleep_watch_impressions1", @""),FYLocalizedString(@"oxygen_severe", @""),FYLocalizedString(@"sleep_watch_impressions2", @""),FYLocalizedString(@"oxygen_light", @"")];
    }
    return @"";
}

@end
